﻿<?php

//在URL后参加 ?pwd=密码 查看生成密码
date_default_timezone_set('PRC');

$password = '202cb962ac59075b964b07152d234b70'; //123
//   https://raw.githubusercontent.com/att4ck/php-zip/master/style.css 

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="zh-CN">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP在线压缩程序</title>
<!-- css copied from wordpress -->
<style type="text/css">

</style>
</head>

<body>
  <form name="myform" id="myform" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<h1 style="color:#2583ad;">在线压缩ZIP文件程序</h1><br>

<div class="message">
      <p>使用方法:选定要压缩的文件或目录（包含子目录），即可开始压缩。压缩的结果保留原来的目录结构。<br />
<?php 

if(isset($_REQUEST['pwd']) && md5($_REQUEST['pwd']) == $password){
    echo '当前目录：<span class="currentdir">'. dirname(__FILE__) . '</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="'. $_SERVER['PHP_SELF']. '">退出</a>';
} else{
    if(isset($_GET['pwd']) ){
        echo '密码值：<span class="currentdir">'. md5($_GET['pwd']) . '</span>';
    }else{
        echo 'Tips:在URL后参加<span class="currentdir">?pwd=密码</span> 查看生成密码.';
    }
}
                
?>
      </p>
</div>
<?php
if(!isset($_REQUEST["myaction"])):
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
	<tr>
      <td width="11%">验证密码: </td>
      <td width="89%"><input class="mm" name="pwd" type="password" id="password" onkeydown="if(event.ctrlKey&&event.keyCode==13){document.getElementById('login').click();return false};">
      <input type="submit" name="login" id="login" class="jr" value=" 进 入 " /></td>
    </tr>	
    <tr>
      <td><input name="myaction" type="hidden" id="myaction" value="dolist"></td>
      <td>&nbsp;</td>
    </tr>
  </table>
  <script type="text/javascript">    document.getElementById('password').focus();   </script>
<?php

elseif($_REQUEST["myaction"]=="dolist"):

        if(!isset($_REQUEST['pwd']) || empty($_REQUEST['pwd']) ){
            die('请输入密码! <a href="'. $_SERVER['PHP_SELF']. '">Again</a>');
        }
        if(md5($_REQUEST['pwd']) != $password) {
            die('输入的密码不正确！<a href="'. $_SERVER['PHP_SELF']. '">Again</a>');
        }
        
        echo '选择要排除的目录(相对路径，以英文半角逗号分隔):<br />';
        echo '<input type="text" id="toexlude" name="toexlude" size="100" /><br />';
	echo "选择要压缩的文件或目录：<br/>";
        
  	$fdir = opendir('./');
	while($file=readdir($fdir)){
		if($file=='.'|| $file=='..' ) continue;
		echo "<input name='dfile[]' type='checkbox' value='$file' ".($file==basename(__FILE__)?"":"checked")."> ";
		if(is_file($file)){
			echo "<span class='myfilename'>文件: $file</span><br>";
		}else{
			echo "<span class='mydirname'>目录: $file</span><br>";
		}
	}
        
?>
<br>
保存目录: 
<input name="todir" type="text" class="ml" id="todir" value=""> (留空为本目录,必须有写入权限)
<!--
value="_zipfiles<?php echo substr(md5(time()),0,8);?>_"
-->
<br>
<br>
文件名称:
<input name="zipname" type="text" class="mc" id="zipname" value="zip">
(.zip)
<!--value="backup_<?php echo substr(md5(__FILE__),0,8);?>.zip"-->
<br>
<br> 
<input name="pwd" type="hidden" id="password" value="<?php echo $_POST['pwd'];?>">
<input name="myaction" type="hidden" id="myaction" value="dozip">
<input class="fx" type='button' value='反选' onclick='selrev();'>
<input class="ys" type="submit" name="Submit" value=" 开 始 压 缩 ">
<script language='javascript'>
function selrev() {
	with(document.getElementById('myform')){
		for(i=0;i<elements.length;i++) {
			thiselm = elements[i];
			if(thiselm.name.match(/dfile\[]/))	thiselm.checked = !thiselm.checked;
		}
	}
}
</script>
<?php

elseif($_REQUEST["myaction"]=="dozip"):

//  set_time_limit(0);

 
        require_once 'PHPzip.php';
	
        if(!trim($_REQUEST['zipname'])) {
            $_REQUEST['zipname'] = 'backup_'.substr(md5(__FILE__),0,8). '.zip'; 
        }else {
            $_REQUEST['zipname'] = trim($_REQUEST['zipname']);
        }
	if(!strrchr(strtolower($_REQUEST['zipname']),'.')=='.zip') {
            $_REQUEST['zipname'] .= ".zip";
        }
	$_REQUEST['todir'] = str_replace('\\','/',trim($_REQUEST['todir']));
	if(!strrchr(strtolower($_REQUEST['todir']),'/')=='/'){ 
            $_REQUEST['todir'] .= "/";	
        }
	if($_REQUEST['todir']=="/") {
		$_REQUEST['todir'] = "./";
        }
	function listfiles($dir="."){
		global $faisunZIP;
		$sub_file_num = 0;

		if(is_file($dir)){
		  if(realpath($faisunZIP->gzfilename)!=realpath($dir)){
			$faisunZIP -> addfile(implode('',file($dir)),$dir);
			return 1;
		  }
			return 0;
		}
		
		$handle=opendir($dir);
		//添加排除
		$to_exlude = !empty($_POST['toexlude']) ? $_POST['toexlude'] :'';
		$exlude = empty($to_exlude) ? array() : explode(',',$to_exlude);
		while ($file = readdir($handle)) {
		   if($file=="."||$file==".." || $file == 'wp-content' )continue;
		   if(is_dir("$dir/$file") && !in_array("$dir/$file",$exlude) )
		   {
			 $sub_file_num += listfiles("$dir/$file");
		   }
		   else {
		   	   if(realpath($faisunZIP ->gzfilename)!=realpath("$dir/$file")){
			     $faisunZIP -> addfile(implode('',file("$dir/$file")),"$dir/$file");
				 $sub_file_num ++;
				}
		   }
		}
		closedir($handle);
		if(!$sub_file_num) $faisunZIP -> addfile("","$dir/");
		return $sub_file_num;
	}

	function num_bitunit($num){
	  $bitunit=array(' B',' KB',' MB',' GB');
	  for($key=0;$key<count($bitunit);$key++){
		if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
		  $num_bitunit_str=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
		}
	  }
	  return $num_bitunit_str;
	}
	
	if(is_array($_REQUEST['dfile'])){
            $faisunZIP = new PHPzip;
            if($faisunZIP -> startfile($_REQUEST['todir'].$_REQUEST['zipname'])){
                echo "正在添加压缩文件...<br><br>";
                $filenum = 0;
                foreach($_REQUEST['dfile'] as $file){
                        if(is_file($file)){
                                echo "<span class='myfilename'>文件: $file </span><br>";
                        }else{
                                echo "<span class='mydirname'>目录: $file </span><br>";
                        }
                        $filenum += listfiles($file);
                }
                $faisunZIP -> createfile();
                echo "<br>压缩完成,共添加 $filenum 个文件.<br /><a href='" .$_REQUEST['todir'].$_REQUEST['zipname']. "'>". $_REQUEST['todir'].$_REQUEST['zipname']." (".num_bitunit(filesize("$_REQUEST[todir]$_REQUEST[zipname]")).")</a>";
            }else{
                echo $_REQUEST['todir'].$_REQUEST['zipname'].'不能写入,请检查路径或权限是否正确.<br>';
            }
	}else{
            echo "没有选择的文件或目录.<br>";
	}


endif;

?>
    
  </form>
  <div id="footer">
  <p><a href="javascript:;" onclick="scrollTo(0,0);" title="返回顶部">TOP</a></p>
  </div>
</body>
</html>
